//
//  SingleTopUpViewController.m
//  AllFamily
//
//  Created by chirui on 2018/6/4.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "SingleTopUpViewController.h"

@interface SingleTopUpViewController (){
    
    NSString * _payType;
    NSString * pay_pwdStr;
    
}
@property (weak, nonatomic) IBOutlet UITextField *moneyText;
@property (weak, nonatomic) IBOutlet UIButton *wxBtn;
@property (weak, nonatomic) IBOutlet UIButton *zfbBtn;
@property (weak, nonatomic) IBOutlet UIButton *balanceBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@end

@implementation SingleTopUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    TitleView(@"充值额度");
    _payType  = @"wxpay";
    self.wxBtn.selected = YES;
    self.sureBtn.layer.cornerRadius = 4.f;
    self.sureBtn.layer.masksToBounds = YES;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];

    // 支付密码输入框
    self.verifyCodeInputView = [[VerifyCodeInputView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-SH_TopHeight)];
    self.verifyCodeInputView.inputView.delegate = self;
    [self.verifyCodeInputView setHidden:YES];
    [self.view addSubview:self.verifyCodeInputView];
    
    //微信
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(payWxResultOpt:)
                                                 name: WX_NOTIFY_KEY
                                               object:nil];
    
    //支付宝
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(ZFBSuccess:)
                                                 name: @"zfb"
                                               object:nil];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)wxBtnClick:(id)sender {
   
    _payType = @"wxpay";
    self.wxBtn.selected = YES;
    self.zfbBtn.selected = NO;
    self.balanceBtn.selected = NO;
}
- (IBAction)zfbBtnClick:(id)sender {
    _payType = @"alipay";
    self.wxBtn.selected = NO;
    self.zfbBtn.selected = YES;
    self.balanceBtn.selected = NO;
    
}
- (IBAction)blanceBtnCick:(id)sender {
    _payType = @"blance";
    self.wxBtn.selected = NO;
    self.zfbBtn.selected = NO;
    self.balanceBtn.selected = YES;
    
}
- (IBAction)sureBtnClick:(id)sender {
    
    if (_moneyText.text.length==0||_moneyText.text ==nil) {
        
        SHuiMBhudTextTimeStr(@"充值金额不能为空！");
        
        return;
    }
    if ([_moneyText.text intValue]<=0) {
        
        SHuiMBhudTextTimeStr(@"充值金额无效，请重新输入！");
        
        return;
    }
    
    if ([_payType isEqualToString:@"blance"]) {
        
        [self checkPayPasswordSetting];
    }else{
        
          [self topUpBanceRequest];
    }
}


- (void)checkPayPasswordSetting {
    
    [self.verifyCodeInputView setHidden:NO];
    [self.verifyCodeInputView.inputView.textFieldArray[0] becomeFirstResponder];
}

#pragma mark - 支付密码输入完成回调
- (void)inputFinishedWithText:(NSString *)text {
    // text为用户输入的6位密码
    
    self.verifyCodeInputView.hidden = YES;
    pay_pwdStr = text;
    for(UITextField *textField in self.verifyCodeInputView.inputView.textFieldArray) {
        textField.text = @"";
    }
    
    if (pay_pwdStr.length!=6) {
        [SHJudgeTools MBProgressHUDPromptWith:@"支付密码格式不正确" On:self.view];
        return;
    }else {
        
        [self serverRequestFor:pay_pwdStr];
        
    }
    
}

-(void)topUpBanceRequest {
    
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"price":_moneyText.text,
                           @"pay_type":_payType,
                           @"type":@"service"
                           };
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(topMoney_payFor_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        
        if ([responseObject[@"code"] intValue]==200) {
            
            if ([_payType isEqualToString:@"wxpay"]) {
                
                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [responseObject[@"datas"][@"Appparam"] objectForKey:@"appid"];
                req.partnerId           = [responseObject[@"datas"][@"Appparam"] objectForKey:@"partnerid"];
                req.prepayId            = [responseObject[@"datas"][@"Appparam"] objectForKey:@"prepayid"];
                req.nonceStr            = [responseObject[@"datas"][@"Appparam"] objectForKey:@"noncestr"];
                req.timeStamp           = [[responseObject[@"datas"][@"Appparam"] objectForKey:@"timestamp"] intValue];
                req.package             = [responseObject[@"datas"][@"Appparam"] objectForKey:@"packages"];
                req.sign                = [responseObject[@"datas"][@"Appparam"] objectForKey:@"sign"];
                
                [WXApi sendReq:req];
                
            }else {
                
                NSString *appScheme = @"AllFamily";
                
                [[AlipaySDK defaultService] payOrder:responseObject[@"datas"][@"pay_string"]  fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    NSLog(@"reslut = %@",resultDic);
                    
                }];
            }
        } else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
}

-(void)serverRequestFor:(NSString *)str{
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"price":_moneyText.text,
                           @"pay_password":str
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(service_balace_api) andparameters:dic Success:^(id responseObject) {
        
        if (codeSucess) {
            
            SHuiMBhudTextTimeStr(@"提交成功");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else {
            
            if ([responseObject[@"code"] intValue]==220) {
                
                USER_DEFAULTSet(@"", @"token");
                USER_DEFAULTSet(@"no", @"enter");
                USER_DEFAULTSet(@"no", @"tokenVerify");
                USER_DEFAULTSet(@"", @"mid");
                
            }
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
    
}

//微信支付完成通知
-(void)payWxResultOpt:(NSNotification *)notification
{
    PayResp *response=(PayResp*)notification.object;
    
    if (response.errCode == WXSuccess)
    {
        
        UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功了！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alerte.tag = 10001;
        [alerte show];
        
    }
    else
    {
        UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付失败了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alerte show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 10001) {
        if (buttonIndex == 0) {
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}
-(void)ZFBSuccess:(NSNotification *)notification {
    
    UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alerte.tag = 10001;
    [alerte show];
}

-(void)dealloc{
    
    //第一种方法.这里可以移除该控制器下的所有通知
    
    NSLog(@"移除了所有的通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


@end
